package com.jilian.mydemo.modul.order.ui;

import android.Manifest;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.jilian.mydemo.MyApplication;
import com.jilian.mydemo.R;
import com.jilian.mydemo.base.BaseActivity;
import com.jilian.mydemo.base.BaseDto;
import com.jilian.mydemo.common.dto.FinishPayDto;
import com.jilian.mydemo.dialog.nicedialog.BaseNiceDialog;
import com.jilian.mydemo.dialog.nicedialog.NiceDialog;
import com.jilian.mydemo.dialog.nicedialog.ViewConvertListener;
import com.jilian.mydemo.dialog.nicedialog.ViewHolder;
import com.jilian.mydemo.modul.order.viewmodel.OrderViewModel;
import com.jilian.mydemo.modul.user.activity.RealNameAuthenticationActivity;
import com.jilian.mydemo.utils.DateUtil;
import com.jilian.mydemo.utils.EmptyUtils;
import com.jilian.mydemo.utils.MainRxTimerUtil;
import com.jilian.mydemo.utils.PermissionsObserver;
import com.jilian.mydemo.utils.ToastUitl;
import com.jilian.mydemo.utils.selectphoto.SelectPhotoUtils;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.jilian.mydemo.Constant.FINALVALUE.FILE_PROVIDER;


public class PayUploadActivity extends BaseActivity {

    private ImageView ivAdd;
    private ImageView ivCloseOne;
    private TextView tvOk;
    private OrderViewModel viewModel;
    private TextView tvHour;
    private TextView tvMin;
    private TextView tvSecond;
    private TextView tvMoney;



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyApplication.addActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.removeActivity(this);
        MainRxTimerUtil.cancel();

    }

    @Override
    protected void createViewModel() {
        viewModel = ViewModelProviders.of(this).get(OrderViewModel.class);
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_pay_upload;
    }

    @Override
    public void initView() {
        setNormalTitle("支付订单", v -> finish());
        ivAdd = (ImageView) findViewById(R.id.iv_add);
        ivCloseOne = (ImageView) findViewById(R.id.iv_close_one);
        tvOk = (TextView) findViewById(R.id.tv_ok);
        tvHour = (TextView) findViewById(R.id.tv_hour);
        tvMin = (TextView) findViewById(R.id.tv_min);
        tvSecond = (TextView) findViewById(R.id.tv_second);
        tvMoney = (TextView) findViewById(R.id.tv_money);
        tvMoney.setText(getIntent().getStringExtra("totalMoney"));
        Long delTime = getIntent().getLongExtra("delTime",0);
        //startTimeTask(delTime);
    }
    private void startTimeTask(long delTime) {
        MainRxTimerUtil.interval(1000, new MainRxTimerUtil.IRxNext() {
            @Override
            public void doNext() {//获取现在的 时分秒 时间戳

                if (delTime > 0) {
                    String str = DateUtil.timeToHms(delTime);
                    tvHour.setText(str.split(":")[0]);
                    tvMin.setText(str.split(":")[1]);
                    tvSecond.setText(str.split(":")[2]);

                } else {
                    finish();
                }

            }
        });
    }

    @Override
    public void initData() {

    }

    @Override
    public void initListener() {
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!EmptyUtils.isNotEmpty(files)) {
                    ToastUitl.showImageToastTips("请上传照片!");
                    return;
                }
                finishPay(getIntent().getStringExtra("orderId"), "3", files);
            }
        });
        ivAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showSelectPhotoTypeDialog();
            }
        });
        ivCloseOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ivAdd.setImageResource(R.drawable.image_add_photo);
                ivCloseOne.setVisibility(View.GONE);
            }
        });

    }

    private void finishPay(String orderId, String type, List<File> fileList) {
        showLoadingDialog();
        viewModel.finishPay(orderId, type, fileList);
        viewModel.getFinishPayliveData().observe(this, new Observer<BaseDto<FinishPayDto>>() {
            @Override
            public void onChanged(@Nullable BaseDto<FinishPayDto> baseDto) {
                hideLoadingDialog();
                if (baseDto.isSuccess()) {
                    Intent intent = new Intent(PayUploadActivity.this, PaySuccessActivity.class);
                    intent.putExtra("type", getIntent().getStringExtra("type"));
                    intent.putExtra("totalMoney", getIntent().getStringExtra("totalMoney"));
                    intent.putExtra("orderId", getIntent().getStringExtra("orderId"));
                    intent.putExtra("orderDto", getIntent().getSerializableExtra("orderDto"));
                    startActivity(intent);
                    finish();
                    MyApplication.clearSpecifyActivities(new Class[]{ThreeOrderDetaiPayActivity.class});

                    MyApplication.clearSpecifyActivities(new Class[]{
                            ThreeOrderDetaiCommitelActivity.class});
                    MyApplication.clearSpecifyActivities(new Class[]{ThreeOrderDetailActivity.class});

                    MyApplication.clearSpecifyActivities(new Class[]{FinishOrderActivity.class, });

                    MyApplication.clearSpecifyActivities(new Class[]{InputServiceDataActivity.class, });

                } else {
                    ToastUitl.showImageToastTips(baseDto.getMsg());
                }

            }
        });
    }

    private List<File> files = new ArrayList<>();
    //相机
    private final int FROM_CAPTURE = 10001;
    //相册
    private final int FROM_ALBUM = 10002;

    /**
     * 选中照片
     */
    private void showSelectPhotoTypeDialog() {
        NiceDialog.init()
                .setLayoutId(R.layout.dialog_photo_select)
                .setConvertListener(new ViewConvertListener() {
                    @Override
                    public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                        dialog.setOutCancel(false);
                        Button btnTakingPictures = (Button) holder.getView(R.id.btn_taking_pictures);
                        Button btnPhotoAlbum = (Button) holder.getView(R.id.btn_photo_album);
                        Button btnCancel = (Button) holder.getView(R.id.btn_cancel);
                        btnCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialog.dismiss();
                            }
                        });
                        //拍照
                        btnTakingPictures.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialog.dismiss();
                                RxPermissions.getInstance(PayUploadActivity.this).request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new PermissionsObserver() {
                                    @Override
                                    protected void onGetPermissionsSuccess() {
                                        SelectPhotoUtils.fromCapture(PayUploadActivity.this, FILE_PROVIDER, FROM_CAPTURE);
                                    }

                                    @Override
                                    protected void onGetPermissionsSuccessFailuer() {
                                        ToastUitl.showImageToastTips("相机权限被拒绝，无法使用拍照功能");
                                    }
                                });

                            }
                        });
                        //相册
                        btnPhotoAlbum.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialog.dismiss();

                                RxPermissions.getInstance(PayUploadActivity.this).request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new PermissionsObserver() {
                                    @Override
                                    protected void onGetPermissionsSuccess() {
                                        SelectPhotoUtils.fromAlbum(PayUploadActivity.this, FILE_PROVIDER, 1, FROM_ALBUM);
                                    }

                                    @Override
                                    protected void onGetPermissionsSuccessFailuer() {
                                        ToastUitl.showImageToastTips("相机权限被拒绝，无法使用拍照功能");
                                    }
                                });

                            }

                        });

                    }
                })
                .setShowBottom(true)
                .show(getSupportFragmentManager());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                //图库
                case FROM_ALBUM:
                    List<Uri> uriList = SelectPhotoUtils.albumResult(data);
                    Uri uri = uriList.get(0);
                    initPath(SelectPhotoUtils.getRealPathFromURI(this, uri));
                    break;
                //相机
                case FROM_CAPTURE:
                    initPath(SelectPhotoUtils.capturePathResult());
                    break;
            }

        }
    }

    /**
     * 设置图片地址
     *
     * @param url
     */
    private void initPath(String url) {
        ivCloseOne.setVisibility(View.VISIBLE);

        Glide
                .with(this)
                .load(url)
                .into(ivAdd);
        files.clear();
        File file = new File(url);
        files.add(file);


    }
}
